package com.clstu.dao_.dao;

import com.clstu.dao_.utils.JdbcUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 这是所有 XxxDAO的父类,提供共有的功能(提供连接,释放资源等,
 * 调用者无需关心其他,只需调用方法和传入参数(sql,Class等)就可以支持crud操作了(不在需要调用者建立连接和释放资源了))
 */
//因为返回的集合也是需要用到泛型的 return ArrayList<T>
//这里用泛型是为了便于子类XxxDao继承父类的时候直接用extend BasicDao<Xxx>就可以了
public class BasicDAO<T> {
    private QueryRunner qr = new QueryRunner();
    private Connection connection = null;

    //编写方发实现dlm(增删改) /返回受影响的行数
    public int update(String sql,Object... parameters){
        try {
            connection = JdbcUtilsByDruid.getConnection();
            int i = qr.update(connection, sql, parameters);
            return i;
        } catch (SQLException e) {
            throw new RuntimeException(e);//编译异常转成运行异常,抛出,便于调用者处理
        } finally {
            JdbcUtilsByDruid.close(null,null,connection);
        }
    }

    //编写方法实现返回多个记录结果            泛型的class对象
    public List<T> queryMany(String sql,Class<T> cls, Object... parameters){
        System.out.println(cls);
        try {
            connection = JdbcUtilsByDruid.getConnection();
            //query()方法做的事情最多..
            return qr.query(connection,sql,new BeanListHandler<T>(cls),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);//转换为运行异常抛出,便于调用者的处理
        } finally {
            JdbcUtilsByDruid.close(null,null,connection);
        }
    }

    //编写方法实现返回单个记录结果
    public T querySingle(String sql,Class<T> cls ,Object... parameters){
        try {
            connection = JdbcUtilsByDruid.getConnection();
            return qr.query(connection,sql,new BeanHandler<T>(cls),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtilsByDruid.close(null,null,connection);
        }
    }

    //编写方法实现返回单行单列
    public Object queryScalar(String sql,Object... parameters){
        try {
            connection= JdbcUtilsByDruid.getConnection();
            return qr.query(connection,sql,new ScalarHandler(),parameters);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtilsByDruid.close(null,null,connection);
        }
    }
}
